package org.university.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.university.common.ApiResponse;
import org.university.entity.Teacher;
import org.university.exception.ResourceNotFoundException;
import org.university.service.TeacherService;
import org.university.util.GlobalUtil;

@CrossOrigin
@RestController
@RequestMapping("/teachers")
public class TeacherController {

    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);

    private final TeacherService teacherService;
    private final GlobalUtil globalUtil;

    public TeacherController(TeacherService teacherService, GlobalUtil globalUtil) {
        this.teacherService = teacherService;
        this.globalUtil = globalUtil;
    }

    /**
     * 获取教师分页列表
     *
     * @param page 页码（从0开始）
     * @param size 每页条数
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<Teacher>>> getTeachers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sort) {

        Page<Teacher> teachers = teacherService.findAll(PageRequest.of(page, size));
        return ApiResponse.success(teachers);
    }

    /**
     * 根据ID查询教师
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Teacher>> getTeacherById(@PathVariable String id) {
        return teacherService.findById(id)
                .map(ApiResponse::success)
                .orElseThrow(() -> new ResourceNotFoundException("未找到id为: " + id + " 的教师"));
    }

    /**
     * 创建教师
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Teacher>> createTeacher(@RequestBody Teacher teacher) {
        Teacher savedTeacher = teacherService.save(teacher);
        return ApiResponse.created(savedTeacher);
    }

    /**
     * 更新教师信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Teacher>> updateTeacher(
            @PathVariable String id,
            @RequestBody Teacher teacher) {

        if (teacherService.findById(id).isEmpty()) {
            throw new ResourceNotFoundException("未找到id为: " + id + " 的教师");
        }
        teacher.setTeacherId(id);
        Teacher updatedTeacher = teacherService.save(teacher);
        return ApiResponse.success(updatedTeacher);
    }

    /**
     * 删除教师
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTeacher(@PathVariable String id) {
        if (teacherService.findById(id).isEmpty()) {
            throw new ResourceNotFoundException("未找到id为: " + id + " 的教师");
        }
        teacherService.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    /**
     * 多条件查询教师
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<Page<Teacher>>> searchTeachers(
            @RequestParam(required = false) String teacherId,
            @RequestParam(required = false) String teacherName,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) String birthDate,
            @RequestParam(required = false) String hireDate,
            @RequestParam(required = false) String deptId,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String email,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String sort) {

        globalUtil.validateGender(gender);

        Page<Teacher> result = teacherService.searchTeachers(
                teacherId, teacherName, gender, birthDate, hireDate,
                deptId, title, phone, email, PageRequest.of(page, size));

        return ApiResponse.success(result);
    }
}